package com.example.weatherpromax.ui.weather

import android.os.Bundle
import android.os.PersistableBundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.weatherpromax.R
import com.example.weatherpromax.logic.model.Weather

class WeatherActivity : AppCompatActivity() {

    val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java)}

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.weather)


        //从intent中取出城市名称，城市的经纬度坐标信息，并赋值给viewmodel的相应变量中
        if (viewModel.locationLng.isEmpty()) {
            viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
        }
        if(viewModel.locationLat.isEmpty()) {
            viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
        }
        if(viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }

        //对weatherviewdata对象进行观察，如果该对象发生变化，就调用showweatherinfo方法
        viewModel.weatherLiveData.observe(this, Observer{ result -> val weather = result.getOrNull()
            if (weather != null) {
                showWeatherInfo(weather)
            } else {
                Toast.makeText(this, "获取天气信息失败", Toast.LENGTH_SHORT).show()
            }
        })
        viewModel.refershWeather(viewModel.locationLng, viewModel.locationLat)
    }

    private fun showWeatherInfo(weather: Weather) {

        val realtime = weather.realtime
        val hourly = weather.hourly
        val daily = weather.daily

        //展示当前的天气信息
        //展示当前气温
        val Tem_current = findViewById<TextView>(R.id.Tem_current)
        Tem_current.text = "${realtime.temperature.toInt()}℃"
        //展示当前日照指数
        val Index_dswrf = findViewById<TextView>(R.id.Index_dswrf)
        Index_dswrf.text = "光照强度${realtime.dswrf.toInt()}"

    }
}